
<template>
  <div>
    <!--面包屑 !-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片试图 !-->
    <el-card>
      <!--搜索与添加区域!-->
      <el-row>
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            clearable
            @clear="gatUserList"
            placeholder="请输入内容"
          > </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            solt="append"
            icon="el-icon-search"
            @click="gatUserList"
          ></el-button>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            solt="append"
            icon="el-icon-search"
            @click="addlogVisible=true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表!-->
      <el-table
        :data="UserList"
        border
        stripe
      >
        <el-table-column
          label="#"
          type="index"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        >
        </el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        >
        </el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        >
        </el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          prop="mg_state"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="UserState(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
            <!-- {{scope.row}}-->
          </template>!
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <!-- d定义域插槽!-->
            <!-- 修-->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="ShowEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="ShowDeleMessage(scope.row.id)"
            ></el-button>
<!---分配角色 !-->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="ShowRolesDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域!-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,4,6]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addlogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!--表单效验 -->
      <el-form
        :model="AddForm"
        :rules="AddFormRules"
        ref="AddFormRef"
        label-width="70px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="AddForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="AddForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="AddForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input v-model="AddForm.mobile"></el-input>
        </el-form-item>
        </el-form-item>
      </el-form>
      <!--底部按钮-->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addlogVisible=false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--修改对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="EditDialogVisible"
      width="50%"
      @close="EditClose"
    >
      <el-form
        :model="EditForm"
        :rules="AddFormRules"
        ref="EditFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="EditForm.username"
            disabled
          ></el-input>
        </el-form-item>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="EditForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input v-model="EditForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部-->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="EditUser()"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除确认框 -->
    <!-- <el-button
      type="text"
      @click="open"
    >点击打开 Message Box</el-button> -->
<!--分配角色的对话框 !-->
    <el-dialog
  title="分配角色"
  :visible.sync="SetRolesdialogVisible"
  width="30%"
  >
  <p>当前的用户：{{RolesVaule.username}}</p>
  <p>当前的角色：{{RolesVaule.role_name}}</p>
  <span>分配新角色：</span> 
  <span>
  <el-select v-model="selectedRoeId" placeholder="请选择">
    <el-option
      v-for="item in AllRolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id"
      >
    </el-option>
  </el-select>
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="SetRolesdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="SetRolesdialogVisible = false">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则（自定义规则）
    var checkEmail = (rule, vaule, callback) => {
      //正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (regEmail.test(vaule)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 验证手机号的规则（自定义规则）
    var checkPhone = (rule, vaule, callback) => {
      //正则表达式
      const regPhone =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regPhone.test(vaule)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '', //搜索关键字
        pagenum: 1,
        pagesize: 1,
      },
      UserList: [],
      total: 0,
      value: true,
      addlogVisible: false,
      // 添加用户的表单数据  与表单绑定
      AddForm: {
        username: '', //因为双向绑定了  所以用户输入的会保存到data中
        password: '',
        email: '',
        mobile: '',
      },
      // 添加表单验证规则
      AddFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度3-10', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度3-10', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 3, max: 14, message: '用户名长度3-10', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      // 修
      EditDialogVisible: false,
      // 查询到的数据对象
      EditForm: {}, //保存着修改框当时的数据
// 分配角色开关
      SetRolesdialogVisible:false,
      // 分配角色的信息
      RolesVaule:[],
      // 所有角色列表
      AllRolesList:[],
      // 已选择的角色id
      selectedRoeId:''
    }
  },
  created() {
    // 发起数据请求
    this.gatUserList()
  },
  methods: {
    // 用到￥http的大部分都要await  通过开发文档 必须要传三个参数过去  params用于传参
    async gatUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      // 最好把参数放到本地的data里
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.UserList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 页数条发生变化
    handleSizeChange(NewSize) {
      this.queryInfo.pagesize = NewSize
      this.gatUserList()
    },
    // 页数按钮发生改变
    handleCurrentChange(NewPage) {
      this.queryInfo.pagenum = NewPage
      this.gatUserList()
    },
    // 监听switch开关状态
    async UserState(NewState) {
      console.log(NewState) //以获得了当前状态
      const { data: res } = await this.$http.put(
        `users/${NewState.id}/state/${NewState.mg_state}`
      )
      if (res.meta.status !== 200) {
        NewState.mg_state = !NewState.mg_state
        return this.$message.error('更改失败')
      }
      this.$message.success('更改成功')
    },
    //重置表单
    addDialogClosed() {
      this.$refs.AddFormRef.resetFields()
    },
    //添加用户预效验
    addUser() {
      this.$refs.AddFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return this.$message.error('添加失败')
        //成功则发起用户网络请求
        const { data: res } = await this.$http.post('users', this.AddForm)
        if (res.meta.status != 201) this.$message.error('添加用户失败')
        this.$message.success('添加成功')
        //隐藏对话框
        this.addlogVisible = false
        //重新获取列表数据
        this.gatUserList()
      })
    },
    // 修改对话框
    async ShowEditDialog(id) {
      this.EditDialogVisible = true
      console.log(id)
      //获取数据
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status != 200) this.$message.error('获取失败')
      this.$message.success('获取成功')
      this.EditForm = res.data
    },
    //监听修改用户框的关闭后重置验证
    EditClose() {
      this.$refs.EditFormRef.resetFields()
    },
    //修改用户信息并提交
    EditUser() {
      this.$refs.EditFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return this.$message.error('修改失败')
        //发起用户修改信息请求
        const { data: res } = await this.$http.put(
          'users/' + this.EditForm.id,
          {
            email: this.EditForm.email,
            mobile: this.EditForm.mobile,
          }
        )
        if (res.meta.status != 200) return this.$message.error('修改失败')
        //关闭弹窗
        this.EditDialogVisible = false
        //刷新用户列表
        this.gatUserList
        return this.$message.success('修改成功')
      })
    },
    // 删
    async ShowDeleMessage(id) {
      console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //confirmResult=confirm   表示确认删除  主意是字符串！！！
      //confirmResult=cancel    表示取消删除
      console.log(confirmResult)
      if (confirmResult != 'confirm') return this.$message.info('取消删除成功')
      if (id == 500) return this.$message.info('admin用户无法删除')
      //确认删除后   请求数据库
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      this.gatUserList()
      this.$message.success('删除成功')
    },

    // 分配角色区域
   async ShowRolesDialog(scope){
      // 弹框前获取所有角色列表
      const {data:res}=await this.$http.get('/roles')
this.AllRolesList=res.data
if(res.meta.status!= 200)  return this.$message.errp('获取数据列表失败')
 this.$message.success('获取数据列表成功')
      this.SetRolesdialogVisible=true
      this.RolesVaule=scope
console.log(this.selectedRoeId)

    }
  },
}
</script>
<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
}
</style>